package cn.edu.stu.syllabus.utils;

import android.support.annotation.IntDef;
import android.support.design.widget.AppBarLayout;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Created by daidaijie on 2017/4/3.
 * 用于监听AppBarLayout的折叠回调，在OnOffsetChangedListener的基础上进一步封装
 */

public abstract class AppBarOnStateChangeAdapter implements AppBarLayout.OnOffsetChangedListener {

    // 折叠状态枚举
    private static class CollapsingToolbarLayoutState {
        private static final int EXPANDED = 0;
        private static final int COLLAPSED = 1;
        private static final int INTERNEDIATE = 2;
    }

    @IntDef({CollapsingToolbarLayoutState.EXPANDED,
            CollapsingToolbarLayoutState.COLLAPSED,
            CollapsingToolbarLayoutState.INTERNEDIATE})
    @Retention(value = RetentionPolicy.SOURCE)
    private @interface CollapsingToolbarLayoutStateDef {
    }

    @CollapsingToolbarLayoutStateDef
    private int state;


    /**
     *  对折叠的状态进行封装，调用相应的函数进行处理
     */
    @Override
    public final void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        int titleSize = getToolbarHeight();
        if (verticalOffset == 0) {
            if (state != CollapsingToolbarLayoutState.EXPANDED) {
                state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                onExpanded();
            }
        } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
            if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                state = CollapsingToolbarLayoutState.COLLAPSED; //修改状态标记为折叠
                onCollapsed();
            }
        } else if (Math.abs(verticalOffset) + titleSize >= appBarLayout.getTotalScrollRange()) {
            if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                state = CollapsingToolbarLayoutState.COLLAPSED; //修改状态标记为折叠
                onCollapsedWithTitle();
            }
        } else {
            if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                state = CollapsingToolbarLayoutState.INTERNEDIATE; //修改状态标记为中间
                onInternediate(appBarLayout.getTotalScrollRange(), verticalOffset);
            }
        }
    }

    public void onExpanded() {
    }

    public void onCollapsed() {
    }

    public void onInternediate(int scrollRange, int offset) {
    }

    public void onCollapsedWithTitle() {

    }

    /**
     * 如果对Toolbar折叠状态下进行处理，则需返回Toolbar的高度
     * @return
     */
    public int getToolbarHeight() {
        return 0;
    }

}
